package com.kqb.sgadmin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kqb.sgadmin.mapper.AdminRoleMapper;
import com.kqb.sgadmin.model.AdminRole;
import com.kqb.sgadmin.model.Role;
import com.kqb.sgadmin.service.AdminRoleService;
import com.kqb.sgadmin.service.RoleService;
import com.kqb.sgcommon.base.exception.BusinessException;
import com.kqb.sgcommon.base.utils.ThrowUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author D
 * @description 针对表【t_admin_role(用户角色关联表)】的数据库操作Service实现
 * @createDate 2025-06-16 16:30:54
 */
@Service
public class AdminRoleServiceImpl extends ServiceImpl<AdminRoleMapper, AdminRole>
        implements AdminRoleService {


    @Resource
    private RoleService roleService;

    @Override
    @Transactional
    public void batchInsertRoles(Integer adminId, List<Integer> roleIds) {
        Set<Integer> newRoleIds = new HashSet<>(roleIds);
        //先删除该管理员的管理的所有角色
        this.bacthDelRoles(adminId);
        ArrayList<AdminRole> adminRoles = new ArrayList<>();
        List<Integer> oldRoleIds = roleService.list().stream().map(Role::getId).collect(Collectors.toList());

        for (Integer newRoleId : newRoleIds) {
            if (oldRoleIds.contains(newRoleId)) {
                AdminRole adminRole = new AdminRole();
                adminRole.setAdminId(adminId);
                adminRole.setRoleId(newRoleId);
                adminRoles.add(adminRole);
            }
        }

        ThrowUtils.throwNotIf(this.saveBatch(adminRoles), BusinessException.of("批量插入用户角色失败"));
    }

    @Override
    public int bacthDelRoles(Integer adminId) {
        QueryWrapper<AdminRole> qw = new QueryWrapper<AdminRole>().eq("admin_id", adminId);
        return this.baseMapper.delete(qw);
    }
}




